package com.coscon.controller;

import cn.hutool.system.SystemUtil;
import com.coscon.controller.base.BaseController;
import com.coscon.service.ConfigService;
import com.coscon.utils.ClientIpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登录认证
 */
@RestController
@Slf4j
public class LoginController extends BaseController {

    @Resource
    private ConfigService configService;


    /**
     * 进入登录界面
     *
     * @param request
     * @param errorInfo
     * @return
     */
    @RequestMapping(value = "/",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView index(HttpServletRequest request, @ModelAttribute("errorInfo") String errorInfo

    ) {
        return this.login(request,errorInfo);
    }


    /**
     * 进入登录界面
     *
     * @param request
     * @param errorInfo
     * @return
     */
    @RequestMapping(value = "/login/index",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView login(HttpServletRequest request, @ModelAttribute("errorInfo") String errorInfo

    ) {
        ModelAndView v = new ModelAndView("login");
        String title = "智慧遥控助手/" + SystemUtil.getHostInfo().getAddress();
        v.addObject("title",title);

        String securityIsUser = configService.getSysconfigValByKey("security_is_user");

        if(StringUtils.equalsIgnoreCase(securityIsUser,"on")){
            Subject currentUser = SecurityUtils.getSubject();
            if(currentUser!=null && currentUser.isAuthenticated()){
                //直接进入主页
                String homeUrl = "/jm/manager/home/index";

                v.setViewName("redirect:" + homeUrl);
                return v;
            }
            v.addObject("errorInfo", errorInfo);
        }else{
            //直接进入主页，无需登录
            String homeUrl = "/jm/manager/home/index";
            v.setViewName("redirect:" + homeUrl);
        }
        return v;
    }



    /**
     * 执行登录
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "/login/execLogin",method = {RequestMethod.POST})
    public ModelAndView execLogin(
            HttpServletRequest request, HttpServletResponse response
            , RedirectAttributes model
            //默认登录信息
            , @RequestParam(value = "code", required = true) String code //密文
            , @RequestParam(value = "rememberMe", required = false) String rememberMe //记住
    ) {
        log.debug("code=" + code);
        ModelAndView v = new ModelAndView();
        String result = "/login/index";
        //定义登录错误的ERROR信息提示
        String errorInfo = null;
        boolean rem = StringUtils.equalsIgnoreCase(rememberMe,"on");

        //如果没有错误信息，则进入认证
        if(StringUtils.isBlank(errorInfo)){//否则直接进入
            UsernamePasswordToken token = new UsernamePasswordToken(
                    code
                    , code
                    ,rem//记住登录
                    , ClientIpUtil.getRemoteAddr(request)
            );
            Subject currentUser = SecurityUtils.getSubject();
            try {
                if (!currentUser.isAuthenticated()) {
                    token.setRememberMe(true);//強制不記住密碼
                    currentUser.login(token);
                }
                result = "/jm/manager/home/index";
            } catch (Exception e) {
                log.error(e.getMessage());
                if (StringUtils.startsWithAny(e.getMessage(), "ERROR:")) {
                    errorInfo = e.getMessage();
                } else {
                    errorInfo = "登录认证失败!";
                }
            }
        }
        model.addFlashAttribute("errorInfo", errorInfo);
        log.debug(errorInfo);
        v.setViewName("redirect:" + result);
        log.info("登录界面处理后，跳入：" + v.getViewName());
        return v;
    }




}
